﻿using System.Windows.Media.Imaging;
using System.Windows.Media;
using Microsoft.Kinect;
using System.Windows;
using Kinect.Toolbox.Record;
using System;

namespace DetectingKinectSencor
{
    /// <summary>
    /// The following class was provided by the book 
    /// Microsoft.Press.Programming.with.the.Kinect.for.Windows.Software.Development.Kit.Sep.2012
    /// </summary>
    public class ColorStreamManager : Notifier
    {
        private bool DEBUGon = MainWindow.DEBUGcolorStreamManager;

        //Constuctor
        public WriteableBitmap Bitmap { get; private set; }


        ////////////////////////////////////////////////
        //              update Methode                //
        ////////////////////////////////////////////////


        public void update(PlayColorStream frame)
        {
            if (frame == null)
                return;

            //Create new local variable with the length of the frame
            var pixelData = new byte[frame.PixelDataLength];
            
            //copy pixes from the frame into pixelData object
            frame.CopyPixelDataTo(pixelData);
            
            if (Bitmap == null)
            {
                //Create out of the frames (only a byte array) a writeableBitmap with a certain height and width
                Bitmap = new WriteableBitmap(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr32, null);
            }

            //Stride of an image = The distance in bytes from the beginning of one row of 
            //the image data to the beginning of the next row.
            int stride = Bitmap.PixelWidth * Bitmap.Format.BitsPerPixel / 8;
            
            Int32Rect dirtyRect = new Int32Rect(0, 0, Bitmap.PixelWidth, Bitmap.PixelHeight);
            
            Bitmap.WritePixels(dirtyRect, pixelData, stride, 0);
            
            // Update calls RaisePropertyChanged(from the Notifierclass) on the Bitmapproperty to 
            // signal that the bitmap has been updated.
            RaisePropertyChanged(() => Bitmap);
        }
    }
}